package com.jstyle.jclifexd.fragment;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Point;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.Spannable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.GroundOverlayOptions;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.Polyline;
import com.amap.api.maps.model.PolylineOptions;
import com.amap.api.maps.model.VisibleRegion;
import com.jstyle.jclifexd.NetWork.NetWorkUtil;
import com.jstyle.jclifexd.R;
import com.jstyle.jclifexd.daoManager.PathRecordDaoManager;
import com.jstyle.jclifexd.daoManager.UserInfoDaoManager;
import com.jstyle.jclifexd.model.PathRecord;
import com.jstyle.jclifexd.model.UserInfo;
import com.jstyle.jclifexd.utils.DateUtil;
import com.jstyle.jclifexd.utils.ImageUtils;
import com.jstyle.jclifexd.utils.MapUtil;
import com.jstyle.jclifexd.utils.PathSmoothTool;
import com.jstyle.jclifexd.utils.ResolveData;
import com.jstyle.jclifexd.utils.SchedulersTransformer;
import com.jstyle.jclifexd.utils.ScreenUtils;
import com.jstyle.jclifexd.utils.WeakDataHolder;
import com.jstyle.jclifexd.view.HeadCircleView;

import java.text.NumberFormat;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link ShareFirstFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ShareFirstFragment extends Fragment implements AMap.OnMapLoadedListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private static final String fast_Pace = "fastPace";
    private static final String low_Pace = "lowPace";
    @BindView(R.id.mapView)
    MapView mapView;
    @BindView(R.id.tv_slowst)
    TextView tvSlowst;
    @BindView(R.id.tv_fast)
    TextView tvFast;
    @BindView(R.id.iv_share_pace)
    ImageView ivSharePace;
    @BindView(R.id.tv_exerciseTime)
    TextView tvExerciseTime;
    @BindView(R.id.tv_Pace)
    TextView tvPace;
    @BindView(R.id.tv_cal)
    TextView tvCal;
    @BindView(R.id.ll_data)
    LinearLayout llData;

    @BindView(R.id.iv_share_icon)
    ImageView ivShareIcon;

    Unbinder unbinder;
    @BindView(R.id.tv_distance)
    TextView tvDistance;
    @BindView(R.id.tv_share_userId)
    TextView tvShareUserId;
    @BindView(R.id.tv_share_time)
    TextView tvShareTime;
    @BindView(R.id.bt_device_name)
    Button btDeviceName;

    @BindView(R.id.iv_share_userIcon)
    ImageView ivShareUserIcon;
    @BindView(R.id.CardView)
    android.support.v7.widget.CardView CardView;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;
    private AMap mAMap;
    private List<LatLng> mOriginLatLngList;
    private List<LatLng> pathoptimizeList;
    private Marker mOriginEndMarker;
    private Marker mOriginStartMarker;
    private Polyline mOriginPolyline;
    String fastPaceString;
    String lowPaceString;

    public ShareFirstFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment ShareFirstFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static ShareFirstFragment newInstance(String param1, String param2, String fastPace, String lowPace) {
        ShareFirstFragment fragment = new ShareFirstFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        args.putString(fast_Pace, fastPace);
        args.putString(low_Pace, lowPace);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
            fastPaceString = getArguments().getString(fast_Pace);
            lowPaceString = getArguments().getString(low_Pace);
        }
    }

    private final static int AMAP_LOADED = 2;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case AMAP_LOADED:
                    //useOMCMap();
                    setupRecord();
                    break;
                default:
                    break;
            }
        }
    };

    private void setupRecord() {
        if (mOriginLatLngList == null || mOriginLatLngList.size() == 0) return;
        PathSmoothTool mpathSmoothTool = new PathSmoothTool();
        mpathSmoothTool.setIntensity(4);
        pathoptimizeList = mpathSmoothTool.pathOptimize(mOriginLatLngList);
        if (pathoptimizeList.size() == 0) return;
        addOriginTrace(pathoptimizeList);
    }

    private int[] colorList = {0xFF7DFF00, 0xFFE1E618, 0xFFFBE01C, 0xfff55638};

    private void addOriginTrace(
            final List<LatLng> originList) {
        LatLng startLatLng = originList.get(0);
        LatLng endLatLng = originList.get(originList.size() - 1);
        int color = Color.GREEN;
        int blendCorlor = 0;
        Log.i(TAG, "addOriginTrace: ");
//        for(int i=0;i<originList.size();i++){
//            blendCorlor=color;
//            if(i==0){
//
//            }else{
//                LatLng latLngLast=originList.get(i-1);
//                LatLng latLng=originList.get(i);
//                double distance= AMapUtils.calculateLineDistance(latLngLast,latLng);
//
//                if(distance<16){
//                    blendCorlor = colorList[0];
//                }else if(distance<=20){
//                    blendCorlor =colorList[1];
//                }else if(distance<=24){
//                    blendCorlor=colorList[2];
//                }else {
//                    blendCorlor=colorList[3];
//                }
//
//            }
//
//            listColor.add(blendCorlor);
//        }
//        mAMap.addPolygon(new PolygonOptions()
//                .addAll(createRectangle(startLatLng,10,10)).fillColor(Color.parseColor("#2f000000")).strokeWidth(1));

        mOriginPolyline = mAMap.addPolyline(new PolylineOptions()
                .width(ScreenUtils.dip2px(getActivity(), 6)).color(
                        Color.GREEN).addAll(originList).useGradient(true).zIndex(12));
        mOriginStartMarker = mAMap.addMarker(new MarkerOptions().position(
                startLatLng).icon(
                BitmapDescriptorFactory.fromResource(R.drawable.start)));
        mOriginEndMarker = mAMap.addMarker(new MarkerOptions().position(
                endLatLng).icon(
                BitmapDescriptorFactory.fromResource(R.drawable.end)));
        int padding = ScreenUtils.dip2px(getContext(), 120);
        int height = mapView.getHeight();
        LatLngBounds latLngBounds = getBounds();
        mAMap.animateCamera(CameraUpdateFactory.newLatLngBounds(latLngBounds, height / 5), new AMap.CancelableCallback() {
            @Override
            public void onFinish() {
                CameraPosition cameraPosition = mAMap.getCameraPosition();
                LatLng latLng = cameraPosition.target;
                VisibleRegion visibleRegion = mAMap.getProjection().getVisibleRegion();
                LatLng latLngFarLeft = visibleRegion.farLeft;
                LatLng latLng1NearLeft = visibleRegion.nearLeft;

                LatLng latLng1NearRight = visibleRegion.nearRight;
                float distanceHeight = AMapUtils.calculateLineDistance(latLngFarLeft, latLng1NearLeft);

                float distanceWidth = AMapUtils.calculateLineDistance(latLngFarLeft, latLng1NearRight);


                Point pointCamera = mAMap.getProjection().toScreenLocation(latLng);
                //   Log.i(TAG, "addOriginTrace: "+pointCamera.x+" "+pointCamera.y);
                Log.i(TAG, "addOriginTrace:  " + distanceHeight + " distance " + distanceWidth);
                float showLength=Math.max(distanceHeight,distanceWidth)*1.5f;
                mAMap.addGroundOverlay(new GroundOverlayOptions()
                        .position(latLng, showLength, showLength)
                        .image(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                                .decodeResource(getActivity().getResources(), R.drawable.ic_marker_bottom))).zIndex(10));
            }

            @Override
            public void onCancel() {

            }
        });
        // Point point=mAMap.getProjection().toScreenLocation(endLatLng);


    }

    private LatLngBounds getBounds() {
        LatLngBounds.Builder b = LatLngBounds.builder();
        if (pathoptimizeList == null) {
            return b.build();
        }
        for (int i = 0; i < pathoptimizeList.size(); i++) {
            b.include(pathoptimizeList.get(i));
        }
        return b.build();

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_share_first, container, false);
        unbinder = ButterKnife.bind(this, view);
        mapView.onCreate(savedInstanceState);
        init();
        return view;
    }


    private void init() {
        initMap();
        NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.ENGLISH);
        numberFormat.setMaximumFractionDigits(2);
        numberFormat.setMinimumFractionDigits(2);
        numberFormat.setGroupingUsed(false);
        PathRecord pathRecord = PathRecordDaoManager.getPathRecord(mParam2);
        String distance = pathRecord.getMDistance();
        int exerciseTime = Integer.valueOf(pathRecord.getMDuration());
        String showDistance = ResolveData.getShowDistance(String.valueOf(distance));
        String showPace = ResolveData.getShowPace(getActivity(), pathRecord.getMAveragespeed());
        String cal = pathRecord.getCalString();
        String duration = DateUtil.getSportTime(exerciseTime);
        showDistance(showDistance, ResolveData.getDistanceLabel());
        showData(duration, showPace, cal);
        tvShareTime.setText(DateUtil.getShareShowDate(getContext(),mParam2));
        tvFast.setText(fastPaceString);
        tvSlowst.setText(lowPaceString);
        String uid = NetWorkUtil.getUserId();
        UserInfo userInfo = UserInfoDaoManager.getUserByUid(uid);
        if (userInfo != null) {
            String name = userInfo.getName();
            if (!TextUtils.isEmpty(name)) tvShareUserId.setText(name);
            Uri iconUri = ImageUtils.getIconUri(getActivity(), userInfo.getUserId());
            Bitmap bmHead = ImageUtils.findHeadBitmap(getActivity(), iconUri);
            bmHead = bmHead == null ? BitmapFactory.decodeResource(getActivity().getResources(),
                    R.drawable.share_icon) : bmHead;
            HeadCircleView circleView = new HeadCircleView(bmHead);
            ivShareUserIcon.setImageDrawable(circleView);
        }
    }

    private void showDistance(String showDistance, String label) {
        String showData = showDistance + label;
        Spannable spannable = ScreenUtils.getSpannable(showData, showDistance, 32);
        tvDistance.setText(spannable);
    }

    private void showData(String time, String pace, String cal) {
        String showTime = getString(R.string.Exercise_time) + "\n" + time;
        String showPace = getString(R.string.avg_pace) + "\n" + pace;
        String showCal = getString(R.string.share_cal_label) + "\n" + cal;
        tvCal.setText(ScreenUtils.getSpannable(showCal, cal, 15));
        tvPace.setText(ScreenUtils.getSpannable(showPace, pace, 15));
        tvExerciseTime.setText(ScreenUtils.getSpannable(showTime, time, 15));
    }

    private void initMap() {
        mOriginLatLngList = WeakDataHolder.getInstance().getData();
        if (mAMap == null) {
            mAMap = mapView.getMap();
            UiSettings uiSettings = mAMap.getUiSettings();
            uiSettings.setScrollGesturesEnabled(false);
            uiSettings.setZoomGesturesEnabled(false);
            uiSettings.setZoomControlsEnabled(false);
            uiSettings.setLogoBottomMargin(-200);
//            uiSettings.setZoomControlsEnabled(false);
            Locale locale = getResources().getConfiguration().locale;
            String language = locale.getLanguage();
            mAMap.setMapLanguage(language);
            mAMap.setOnMapLoadedListener(this);

        }
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onMapLoaded() {
        Message msg = handler.obtainMessage();
        msg.what = AMAP_LOADED;
        handler.sendMessage(msg);
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

    private static final String TAG = "ShareFirstFragment";

    private void shareFile(Bitmap bitmapMap) {
        int h = 0;
        int width = CardView.getWidth();
        for (int j = 0; j < CardView.getChildCount(); j++) {
            h += CardView.getChildAt(j).getHeight();
        }

        final Bitmap bitmap = Bitmap.createBitmap(width, h, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawColor(Color.TRANSPARENT);
        canvas.drawBitmap(bitmapMap, 0, 0, null);
        int layer = canvas.saveLayer(0, 0, width, h, null, Canvas.ALL_SAVE_FLAG);
        CardView.draw(canvas);

        canvas.restoreToCount(layer);
        final String path =mParam2+ "0.jpg";
        Observable.create(new ObservableOnSubscribe<Object>() {
            @Override
            public void subscribe(ObservableEmitter<Object> emitter) throws Exception {
                ScreenUtils.saveShotPic(bitmap, path);
                emitter.onComplete();
            }
        }).compose(SchedulersTransformer.applySchedulers()).subscribe(new Observer<Object>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Object o) {

            }

            @Override
            public void onError(Throwable e) {
                Log.i(TAG, "onError: " + e.getMessage());
            }

            @Override
            public void onComplete() {
                ScreenUtils.shareByPhone(getContext(), path);
            }
        });

    }

    private void getMapBitMap() {
        mAMap.getMapScreenShot(new AMap.OnMapScreenShotListener() {
            @Override
            public void onMapScreenShot(Bitmap bitmap) {
                shareFile(bitmap);
            }

            @Override
            public void onMapScreenShot(Bitmap bitmap, int i) {

            }
        });
    }

    public void shareFile() {
        getMapBitMap();
    }
}
